﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection.Metadata;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz;
using Quartz.Logging;
using Quartz.Impl.Matchers;
using Common;
using CarparkBusiness;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Configuration;
using CarparkIMS_Model;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace CarparkBusiness
{
    public partial class ScheduleFileFlushTask
    { 
        public static string[] Args { get; set; }
        public static bool InRunning { get; set; } = false;
        public static async Task RunTask(string[] args,int intervalMinutes)
        {
            Args = args;
#if DEBUG
            intervalMinutes = 1;
#endif
            DateTime TaskStartDate = DateTime.Now;

            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = await factory.GetScheduler();

                await scheduler.Start();
 
                #region FileFlush
                //================================
                IJobDetail jobFileFlush = JobBuilder.Create<ScheduleFileFlushJob>()
                   .WithIdentity("JobFileFlush", "GroupUnitClac1")
                   .Build();

                int IntervalMinsTodo = 1440;

#if DEBUG
                IntervalMinsTodo = 1;
#endif
                ITrigger triggerFileFlush = TriggerBuilder.Create()
                 .WithIdentity("triggerFileFlush")
                 .StartAt(TaskStartDate) 
                  .ForJob("JobFileFlush", "GroupUnitClac1").WithCalendarIntervalSchedule(w => w
                 .WithIntervalInMinutes(IntervalMinsTodo)).Build();

                await scheduler.ScheduleJob(jobFileFlush, triggerFileFlush);

                #endregion

            }
            catch (SchedulerException se)
            {
                await Console.Error.WriteLineAsync(se.ToString());
            }
        }
         
        public class ScheduleFileFlushJob : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            { 
 
                var services = new ServiceCollection();
               ConfigureServices(services);
                var serviceProvider = services.BuildServiceProvider();  
                await serviceProvider.GetService<FileFlush>().Run(Args);
                string loggerLineJob = string.Format("\n[{0:yyyy-MM-dd HH:mm:ss fff}] [INFO] [Execute::FileFlush.Run:{1}] -  [FILE FLUSH]", DateTime.Now, context.FireInstanceId);
                Common.CommonBase.OperateDateLoger(loggerLineJob);
                await Console.Out.WriteLineAsync(loggerLineJob);
                return; 
            }

            public static void ConfigureServices(IServiceCollection services)
            { 
                services.AddScoped<IBackgroundServiceStatus, BackgroundServiceStatus>();
                var Configuration = TaskStartUp.ReadFromAppSettings(); 
                services.Configure<ParkingSetting>(Configuration.GetSection("parkingSetting"));
                services.AddLogging(builder =>
                { 
                    builder.AddConsole();
                    builder.AddDebug();
                });
                services.AddTransient<FileFlush>();
            }
        } 
    }
}
